package basic.study.wantOffer.chapter3;

import java.util.Scanner;

/**
 * @author Kevin
 * @date 2020/4/9 18:25
 *        | a^(n/2) * a^(n/2)                 ——n是偶数
 * a^n =  |
 *        | a^((n-1)/2) * a^((n-1)/2) * a     ——n是奇数
 */

public class Problem16 {

    public static double powerWithUnsignedExponent(double base, int exponent) {
        if (base == 0) return 0;
        else if (base == 1 || exponent == 0) return 1;

        if (exponent == 1) return base;
        else if (exponent < 0) {
            base = 1 / base;
            exponent = -exponent;
        }

        double result = powerWithUnsignedExponent(base, exponent>>1);
        result *= result;
        if ((exponent & 1) == 1) {
            result *= base;
        }
        return result;
    }

    //还有书上的方法
    boolean isInvalid = false;

    public double power(double base, int exponent) {
        isInvalid  = false;
        double result;//double类型
        if (exponent > 0) {
            result = powerCore(base, exponent);
        } else if (exponent < 0) {
            if (base == 0) {
                isInvalid = true;//0的负数次方不存在
                return 0;
            }
            result = 1 / powerCore(base, -exponent);
        } else {
            return 1;//这里0的0次方输出为1
        }
        return result;
    }

    private double powerCore(double base, int exponent) {
        if (exponent == 1) return base;
        if (exponent == 0) return 1;

        double result = powerCore(base, exponent >> 1);
        result *= result;
        if ((exponent & 0x1) == 1) {
            result *= base;
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double base = sc.nextDouble();
        int exponent = sc.nextInt();
        System.out.println(powerWithUnsignedExponent(base, exponent));
    }
}
